import type { LoginFormData, TokenInfo, User } from '@/api/user/type'
import { login, logout } from '@/api/user'
import { jwtDecode } from 'jwt-decode'
import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', () => {
  const tokenInfo = ref<TokenInfo | any>(null)
  const user = ref<User | any>(null)

  async function doLogin(loginFormData: LoginFormData) {
    tokenInfo.value = await login(loginFormData)
    user.value = jwtDecode(tokenInfo.value.tokenValue)
  }

  const doLogout = async () => {
    await logout()
    tokenInfo.value = null
    user.value = null
  }
  return {
    tokenInfo,
    user,
    doLogin,
    doLogout,
  }
}, {
  persist: true, // 添加这个配置
})
